import storage from 'store'
import { getInfo, login } from '@/api/loginApi'
import { getuserauth } from '@/api/permissionApi'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { welcome } from '@/utils/util'

const user = {
  state: {
    token: '',
    name: '',
    welcome: '',
    avatar: '',
    roles: [],
    info: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, {
      name,
      welcome
    }) => {
      state.name = name
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    }
  },

  actions: {
    // 登录
    Login ({
             commit
           }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(response => {
          if (response.code === 200) {
            // console.log('登录成功!', response)
            const result = response.data
            storage.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
            commit('SET_TOKEN', result.token)
            getInfo().then(res => {
              if (res.code === 200) {
                storage.set('userinfo', res.data, 7 * 24 * 60 * 60 * 1000)
              }
            })
            resolve(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo ({
               commit
             }) {
      return new Promise((resolve, reject) => {
        getInfo().then(response => {
          // console.log('个人信息返回', response)
          if (response.code === 200) {
            storage.set('userinfo', response.data, 7 * 24 * 60 * 60 * 1000)
          }
          // console.log('暂无路由')
          // const result = response.data
          getuserauth().then(res => {
            // console.log('路由表', res.data)
            commit('SET_ROLES', res.data)
            commit('SET_NAME', {
              name: response.data.user,
              welcome: welcome()
            })
            commit('SET_AVATAR', response.data.img)

            resolve(res.data)
          }).catch(err => {
            console.log(err)
          })
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    Logout ({
              commit,
              state
            }) {
      return new Promise((resolve) => {
        // logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        storage.remove(ACCESS_TOKEN)
        localStorage.removeItem('Access-Token')
        localStorage.removeItem('token')
        resolve()
        // }).catch(() => {
        //   resolve()
        // }).finally(() => {
        // })
      })
    }

  }
}

export default user
